<?php
/**
 * (ajax)
 */
namespace App\Admin\Ajax\Inventory;

use App\Models\Basics\SysArea;
use App\Models\Inventory\InventoryCn;
use App\Models\Inventory\PublicCn;
use App\Models\Inventory\Record;
use App\Models\Inventory\Storage;
use App\Models\Product\ProductMixSku;
use App\Models\Product\ProductSku;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\DB;
use App\Util\SerialNo;
class SplitAjax {

    /**
     * 库存拆分
     * @param $param
     * @return \Illuminate\Http\JsonResponse
     */
    public function splitBatch($param){
        try{
            $detail = $param;
            $message = [];
            $storageAt = date('Y-m-d');
            $userId = Admin::user()->id;
            $pAreaId = SysArea::getSysAreaIdByArea(); //Public
            foreach ($detail as $item){
                $pSkuId = $item['psku_id'];
                $splitNum = $item['split_num'];
                if(!$splitNum)continue;
                DB::beginTransaction();

                //公共库存
                $ci = PublicCn::getPublicCnWithLock($pSkuId);
                if(!$ci){
                    DB::rollBack();
                    continue;
                }

                $ps = ProductSku::query()->find($pSkuId);
                $canSplitNum = $ci->instant;
                if($canSplitNum < $splitNum){
                    $message[$ps->psku_code] = $ps->psku_code.'可拆数'.$canSplitNum.'<拆分数'.$splitNum;
                    DB::rollBack();
                    continue;
                }
                $mixRuleArr = ProductMixSku::_mixRuleArrIDAsKey($ps->mix_rule);
                $isTrue = true;
                $storageDetail = [];
                $recordNo = SerialNo::getRcNo();
                foreach($mixRuleArr as $_pSkuId => $_num){
                    $instantNum = $_num * $splitNum;

                    //站点库存
                    $pci = InventoryCn::query()->firstOrNew(['area_id' => $pAreaId,'psku_id' => $_pSkuId]);
                    $pci->instant += $instantNum;
                    $flag1 = $pci->save();
                    if(!$flag1){
                        $isTrue = false;
                        break;
                    }

                    //出入库记录
                    $flag2 = Record::create([
                        'record_no' => $recordNo,
                        'psku_id' => $_pSkuId,
                        'area_id' => $pAreaId,
                        'action_type' => 3,
                        'record_type' => 1,
                        'num' => $instantNum,
                        'user_id' => $userId,
                    ]);
                    if(!$flag2){
                        $isTrue = false;
                        break;
                    }
                    //入库明细
                    $_pSku = ProductSku::getModelById($_pSkuId);
                    $storageDetail[$_pSkuId]['psku_id'] = $_pSkuId;
                    $storageDetail[$_pSkuId]['storage_num'] = $instantNum;
                    $storageDetail[$_pSkuId]['unit_price'] = ProductSku::getPuPrice($_pSku);
                    $storageDetail[$_pSkuId]['unit_price_no_tax'] = 0;
                    $storageDetail[$_pSkuId]['pack_price'] = 0;
                }
                if($isTrue){
                    $ci->instant -= $splitNum;
                    $flag3 = $ci->save();
                    if(!$flag3){
                        DB::rollBack();
                        continue;
                    }
                    $flag4 = Record::create([
                        'record_no' => $recordNo,
                        'psku_id' => $pSkuId,
                        'area_id' => $pAreaId,
                        'action_type' => 3, //拆分
                        'record_type' => 2, //出库
                        'num' => -$splitNum,
                        'user_id' => $userId,
                    ]);
                    if(!$flag4){
                        DB::rollBack();
                        continue;
                    }
                    $storageDetail[$pSkuId]['psku_id'] = $pSkuId;
                    $storageDetail[$pSkuId]['storage_num'] = -$splitNum;
                    $storageDetail[$pSkuId]['unit_price'] = ProductSku::getPuPrice($ps);
                    $storageDetail[$pSkuId]['unit_price_no_tax'] = 0;
                    $storageDetail[$pSkuId]['pack_price'] = 0;
                    self::_receive($storageAt,$userId,$storageDetail);
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }
            if(empty($message)){
                return response()->json(['status' => true, 'message' => '操作成功！']);
            }else{
                return response()->json(['status' => false, 'message' => implode(PHP_EOL,$message)]);
            }
        }catch(\Illuminate\Database\QueryException $ex) {
            DB::rollBack();
            report($ex);
            return response()->json(['status' => false, 'message' => '系统错误']);
        }catch (\Exception $e){
            report($e);
            return response()->json(['status' => false, 'message' => '系统错误']);
        }
    }

    /**
     * 拆分入库记录
     * @param $storageAt
     * @param $userId
     * @param $storageDetail
     */
    private function _receive($storageAt,$userId,$storageDetail){
        DB::beginTransaction();
        $storage = Storage::query()->create([
            'storage_no' => SerialNo::getRsNo(),
            'storage_at' => $storageAt,
            'type' => 3, //拆分入库
            'cuser_id' => $userId
        ]);
        $storage->detail()->createMany($storageDetail);
        DB::commit();
    }
}
